import 'dart:convert';

import 'package:flutter_baselib/lib.dart';

///@date:  2021/2/25 14:22
///@author:  lixu
///@description: 日志拦截器
class LogsInterceptors extends InterceptorsWrapper {
  String _tag = 'HttpLog';

  @override
  onRequest(RequestOptions options) async {
    LogUtils.i(_tag, "****************onRequest() start*******************");
    LogUtils.i(_tag, 'url：${options.baseUrl + options.path}');
    LogUtils.i(_tag, 'headers: ${json.encode(options.headers ?? {})}');
    LogUtils.i(_tag, 'method: ${options.method}');
    LogUtils.i(_tag, 'responseType: ${options.responseType?.toString()}');
    LogUtils.i(_tag, 'followRedirects: ${options.followRedirects}');
    LogUtils.i(_tag, 'connectTimeout: ${options.connectTimeout}');
    LogUtils.i(_tag, 'receiveTimeout: ${options.receiveTimeout}');
    LogUtils.i(_tag, 'extra: ${json.encode(options.extra ?? {})}');
    LogUtils.i(_tag, 'queryParameters: ${json.encode(options.queryParameters ?? {})}');
    LogUtils.i(_tag, 'params: ${json.encode(options.data ?? {})}');
    LogUtils.i(_tag, "****************onRequest() end*********************");
    return options;
  }

  @override
  Future onResponse(Response response) async {
    LogUtils.i(_tag, "****************onResponse() start******************");
    _printResponse(response);
    LogUtils.i(_tag, "****************onResponse() end********************");
    return response;
  }

  void _printResponse(Response response) {
    LogUtils.i(_tag, 'url: ${response.request?.path}');
    LogUtils.i(_tag, 'statusCode: ${response.statusCode}');
    if (response.isRedirect == true) {
      LogUtils.i(_tag, 'redirect: ${response.realUri}');
    }
    LogUtils.i(_tag, 'response headers: ${response.headers?.toString()}');
    LogUtils.i(_tag, 'Response Text: ${response.toString()}');
  }

  @override
  onError(DioError err) async {
    LogUtils.e(_tag, "****************onError() start*********************");
    LogUtils.e(_tag, '请求异常: ${err.toString()}');
    LogUtils.e(_tag, '请求异常信息: ${err.response?.toString()}');
    LogUtils.e(_tag, "****************onError() end***********************");
    return err;
  }
}
